package rahmath.sharif.docrypt;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.UUID;

import javax.crypto.Cipher;

import rahmath.sharif.docrypt.constant.DocryptConstants;
import rahmath.sharif.docrypt.entity.Vault;
import rahmath.sharif.docrypt.util.Docrypt;
import rahmath.sharif.docrypt.util.DocryptUtil;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.app.NavUtils;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Toast;

public class AttachmentsActivity extends ListActivity implements
		DocryptConstants, DocryptInterface {
	private ProgressDialog progressDialog;

	public ProgressDialog getProgressDialog() {
		return progressDialog;
	}

	public Activity getActivity() {
		return this;
	}

	@TargetApi(11)
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_attachments);
		if (Build.VERSION.SDK_INT > Build.VERSION_CODES.HONEYCOMB) {
			getActionBar().setDisplayHomeAsUpEnabled(true);
		}
	}

	@Override
	protected void onStart() {
		super.onStart();
		final Bundle bundle = getIntent().getExtras();
		final Vault vault = DocryptUtil.getVaultFromSD(bundle
				.getString(VAULT_FILE_NAME));
		final String dataKey = bundle.getString(DATA_KEY);
		setListAdapter(new ArrayAdapter<String>(this, R.layout.list_item_vault,
				new ArrayList<String>(vault.getDatas().get(dataKey)
						.getAttachments().keySet())));
		getListView().setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> arg0, View view,
					int position, long length) {
				Intent intentManageAttachment = new Intent(
						AttachmentsActivity.this,
						ManageAttachmentActivity.class);
				intentManageAttachment.putExtra(ATTACHMENT_KEY, getListView()
						.getItemAtPosition(position).toString());
				intentManageAttachment.putExtra(DATA_KEY,
						bundle.getString(DATA_KEY));
				intentManageAttachment.putExtra(VAULT_FILE_NAME,
						bundle.getString(VAULT_FILE_NAME));
				intentManageAttachment.putExtra(VAULT_PASSWORD,
						bundle.getString(VAULT_PASSWORD));
				startActivity(intentManageAttachment);
			}
		});
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.activity_attachments, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			NavUtils.navigateUpFromSameTask(this);
			return true;
		case R.id.attachFile:
			Intent intentChooseFile = new Intent(AttachmentsActivity.this,
					Explorer.class);
			intentChooseFile.putExtra(INTENT_EXTRA_CHOOSE, FILE);
			try {
				intentChooseFile.putExtra(INTENT_EXTRA_FILE_PATH, Environment
						.getExternalStorageDirectory().getCanonicalPath());
			} catch (IOException e) {
				e.printStackTrace();
			}
			startActivityForResult(intentChooseFile, INTENT_CHOOSE_FILE);
			return true;
		case R.id.lockVault:
			Intent vaultsIntent = new Intent(this, VaultsActivity.class);
			vaultsIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			vaultsIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
			startActivity(vaultsIntent);
			return true;
		case R.id.deleteData:
			final Vault vaultDataDel = DocryptUtil.getVaultFromSD(getIntent()
					.getExtras().getString(VAULT_FILE_NAME));
			DialogInterface.OnClickListener confirmDialogDeleteData = new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					switch (which) {
					case DialogInterface.BUTTON_POSITIVE:
						String dataKey = getIntent().getExtras().getString(
								DATA_KEY);
						boolean success1 = DocryptUtil.deleteDataFromSD(
								vaultDataDel, dataKey);
						vaultDataDel.getDatas().remove(dataKey);
						boolean success2 = DocryptUtil
								.putVaultToSD(vaultDataDel);
						if (success1 && success2) {
							Toast.makeText(getApplicationContext(),
									getString(R.string.dataDeleteSuccessful),
									Toast.LENGTH_SHORT).show();
							Intent datasIntent = new Intent(
									AttachmentsActivity.this,
									DatasActivity.class);
							datasIntent
									.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
							datasIntent
									.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
							datasIntent.putExtra(VAULT_FILE_NAME,
									vaultDataDel.getVaultFileName());
							startActivity(datasIntent);
						} else {
							Toast.makeText(getApplicationContext(),
									getString(R.string.dataDeleteFailed),
									Toast.LENGTH_SHORT).show();
						}
						break;
					case DialogInterface.BUTTON_NEGATIVE:
						dialog.dismiss();
						break;
					}
				}
			};
			new AlertDialog.Builder(AttachmentsActivity.this)
					.setCancelable(false)
					.setTitle("Confirm Delete!")
					.setMessage(
							"Data : "
									+ vaultDataDel
											.getDatas()
											.get(getIntent().getExtras()
													.getString(DATA_KEY))
											.getName())
					.setPositiveButton("Delete", confirmDialogDeleteData)
					.setNegativeButton("Cancel", confirmDialogDeleteData)
					.show();
			return true;
		case R.id.deleteVault:
			final Vault vaultDel = DocryptUtil.getVaultFromSD(getIntent()
					.getExtras().getString(VAULT_FILE_NAME));
			DialogInterface.OnClickListener confirmDialogDeleteVault = new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					switch (which) {
					case DialogInterface.BUTTON_POSITIVE:
						boolean success = DocryptUtil
								.deleteVaultFromSD(vaultDel);
						if (success) {
							Toast.makeText(getApplicationContext(),
									getString(R.string.vaultDeleteSuccessful),
									Toast.LENGTH_SHORT).show();
							Intent vaultsIntent = new Intent(
									AttachmentsActivity.this,
									VaultsActivity.class);
							vaultsIntent
									.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
							vaultsIntent
									.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
							startActivity(vaultsIntent);
						} else {
							Toast.makeText(getApplicationContext(),
									getString(R.string.vaultDeleteFailed),
									Toast.LENGTH_SHORT).show();
						}
						break;
					case DialogInterface.BUTTON_NEGATIVE:
						dialog.dismiss();
						break;
					}
				}
			};
			new AlertDialog.Builder(AttachmentsActivity.this)
					.setCancelable(false).setTitle("Confirm Delete!")
					.setMessage("Vault : " + vaultDel.getName())
					.setPositiveButton("Delete", confirmDialogDeleteVault)
					.setNegativeButton("Cancel", confirmDialogDeleteVault)
					.show();
			return true;
		case R.id.help:
			Intent helpActivity = new Intent(this, HelpActivity.class);
			startActivity(helpActivity);
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		String inputFilePath = null;
		switch (requestCode) {
		case INTENT_CHOOSE_FILE:
			if (resultCode == Activity.RESULT_OK) {
				inputFilePath = data.getStringExtra(INTENT_EXTRA_CHOOSEN_PATH);
			}
			break;
		}
		if (null != inputFilePath && 0 != inputFilePath.length()) {
			String password = getIntent().getExtras().getString(VAULT_PASSWORD);
			File sourceFile = new File(inputFilePath);
			if (sourceFile.length() > DocryptUtil.getSpaceAvailable()) {
				Toast.makeText(getApplicationContext(),
						getString(R.string.spaceNotAvailable),
						Toast.LENGTH_SHORT).show();
				return;
			}
			Bundle bundle = getIntent().getExtras();
			Vault vault = DocryptUtil.getVaultFromSD(bundle
					.getString(VAULT_FILE_NAME));
			vault.getDatas().get(bundle.getString(DATA_KEY)).getAttachments()
					.put(sourceFile.getName(), UUID.randomUUID().toString());
			DocryptUtil.putVaultToSD(vault);
			File derivedFile = new File(
					DocryptUtil.getDocryptDir(DOCRYPT_DATAS_ATTACHMENTS), vault
							.getDatas().get(bundle.getString(DATA_KEY))
							.getAttachments().get(sourceFile.getName()));
			final Docrypt docrypt = new Docrypt(this, password, sourceFile,
					derivedFile, Cipher.ENCRYPT_MODE);
			progressDialog = new ProgressDialog(AttachmentsActivity.this);
			progressDialog.setMessage(getString(R.string.encrypting));
			progressDialog.setIndeterminate(false);
			progressDialog.setMax(100);
			progressDialog.setCanceledOnTouchOutside(false);
			progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
			progressDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "Cancel",
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {
							docrypt.cancel(true);
							dialog.dismiss();
						}
					});
			progressDialog
					.setOnKeyListener(new DialogInterface.OnKeyListener() {
						public boolean onKey(DialogInterface dialog,
								int keyCode, KeyEvent event) {
							return true;
						}
					});
			docrypt.execute((String[]) null);
		}
	}
}
